"""
模块-: OA - 蓝图 views视图 模块
@Author          :王海波
@Version         ：V 1.0.0
@CreateTime       ：2020/10/20
-----------------------------------
@ModifyTime       : 2020/10/20
@ModifyContent    : 2020/10/20
@Remark           : 备注


"""
# 导包
import os
import hashlib
import datetime
from functools import wraps   # 对装饰的函数进行设置为自己的函数名

from flask import session
from flask import jsonify
from flask import request
from flask import redirect
from flask import render_template
from flask import make_response

from bluepro.OApro import OApro as app
# from bluepro import csrf
from bluepro.models import *

# 哈希加密
def setPassword(password):
    md5 = hashlib.md5()
    md5.update(password.encode())
    result = md5.hexdigest()
    return result



# cookie 装饰器
def is_cookie(fun):
    @wraps(fun)
    def inner(*args,**kwargs):
        # 对cookie进行判断
        username = request.cookies.get("username")
        user_id = request.cookies.get("user_id")
        if username and user_id:   # 如果有数据
            user = Person.query.get(int(user_id))   # 获取到这个数据
            if user.username == username:    # 判断用户名是否正确
                return fun(*args,**kwargs)    # 返回函数被装饰的功能
        else:
            return redirect("/OA/login/")
    return inner


# 首页
@app.route("/index/",methods = ["GEt","POST"])
@is_cookie
def index():
    return render_template("index.html")


# 登陆
@app.route("/login/", methods = ["GET","POST"])
def login():
    if request.method == "POST":
        username = request.form.get("username")
        password = request.form.get("password")
        # 进行判断
        password = setPassword(password)
        user = Person.query.filter_by(username = username,password=password).first()
        if user:
            # 存在账号跟密码
            response = redirect("/OA/index/")
            response.set_cookie("username", user.username)
            response.set_cookie("user_id", str(user.id))
            session["username"] = username
            return response
    return render_template("login.html")


# 注册
@app.route("/registered/", methods = ["GET","post"])
def registered():
    if request.method == "POST":
        username = request.form.get("username")
        password = request.form.get("password")
        # 将数据进行保存
        person = Person()
        person.username = username
        por = setPassword(password)
        person.password = por
        person.save()
        return redirect("/OA/login/")
    return render_template("registered.html")


#  退出
@app.route("/logout/")
def logout():
    """
    退出就是删除cookie过程
    给浏览器传送一个指令，让浏览器删除cookie
    """
    response =  redirect("/OA/login/")
    response.delete_cookie("username")
    response.delete_cookie("user_id")
    session.get("username")
    session.clear()    # 清空session
    return response



# 接受注册传来的数据，并进行比对
@app.route("/get_registered/")
def get_registered():
    # 获取username的值
    username = request.args.get("re_id")
    if username:
        # 对数据库中的数据进行判断
        if  Person.query.filter(Person.username == username).first():
            reslut = "用户名已经存在"
        else:
            reslut = "用户名可以使用"
        return jsonify({"描述":reslut})


# 新闻首页
@app.route("/news/")
@is_cookie
def news():
    page = request.args.get("news_id",1)
    page = int(page)
    news_list = News.query.filter().order_by(News.public_time.desc()).paginate(page,10)
    # self, page=None, per_page=None, error_out=True, max_per_page=None
    #       offset      limit
    # 'has_next', 'has_prev', 'items', 'iter_pages', 'next', 'next_num', 'page', 'pages', 'per_page', 'prev', 'prev_num', 'query', 'total']

    print(dir(news_list))
    # news_list = db.session.query(News.title,News.author,News.public_time)
    return render_template("news.html",**locals())




# 添加新闻页面
@app.route("/add_news/",methods = ["GET","POST"])
@is_cookie
def add_news():
    if request.method == "POST":
        title = request.form.get("title")
        author = request.form.get("author")
        content = request.form.get("content")
        # 保存图片
        picture = request.files.get("picture")
        # 获得图片名称
        filename = picture.filename
        # 图片保存路径
        path = os.path.join(
            os.path.dirname(
                os.path.dirname(
                    os.path.abspath(__file__)
                )
            ),"static"
        )
        file_path = os.path.join("img", filename)
        save_path = os.path.join(path, file_path)
        picture.save(save_path)
        # 数据表添加信息
        p2 = News()
        p2.title = title
        p2.author = author
        p2.content = content
        p2.picture = file_path
        p2.public_time = datetime.datetime.now()
        p2.save()
        return redirect("/OA/news/")
    return render_template("add_news.html")

# 新闻详情
@app.route("/detail_news/<int:id>/")
@is_cookie
def detail_news(id):
    news = News.query.get(id)
    return render_template("detail_news.html", **locals())

# 编辑新闻页面
@app.route("/edit_news/<int:id>/",methods=["GET","POST"])
@is_cookie
def edit_news(id):
    newst = News.query.get(id)
    if request.method == "POST":
        # 获取到数据
        title = request.form.get("title")
        author = request.form.get("author")
        content = request.form.get("content")
        # 保存图片
        picture = request.files.get("picture")
        if picture :
            # 获取名字
            filename = picture.filename
            # 获取路径
            path = os.path.join(
                os.path.dirname(
                    os.path.abspath(__file__)
                ),"static"
            )
            file_path = os.path.join("img", filename)
            save_path = os.path.join(path, file_path)
            picture.save(save_path)
            newst.picture = file_path
            newst.update()
        else:
            picture = newst.picture
        # 更新数据
        newst.title = title
        newst.author = author
        newst.content = content
        newst.update()
        return redirect("/news/")
    return render_template("edit_news.html", **locals())

# 删除页面
@app.route("/delete_news/<int:id>/")
def delete_news(id):
    news = News.query.get(id)
    news.delete()
    return redirect("/OA/news/")

# permission   权限管理
@app.route("/permission/")
@is_cookie
def permission():
    per_list = Permission.query.all()
    return render_template("permission.html", **locals())

# 个人考勤管理
@app.route("/attendance_me/")
@is_cookie
def attendance_me():
    return render_template("attendance_me.html")

# attendance_subordinate 下属考勤管理
@app.route("/attendance_subordinate/")
@is_cookie
def attendance_subordinate():
    return render_template("attendance_subordinate.html")


# department 部门管理
@app.route("/department/")
@is_cookie
def department():
    dep_list = Department.query.all()
    return render_template("department.html", **locals())


# add_department 添加部门
@app.route("/add_department/", methods=["GET","POST"])
@is_cookie
def add_department():
    # 获取数据
    if request.method == "POST":
        d_name = request.form.get("d_name")
        d_dec = request.form.get("d_dec")
        # 数据库中添加数据
        d1 = Department()
        d1.d_name = d_name
        d1.d_dec = d_dec
        d1.save()
        return redirect("/OA/department/")
    return render_template("add_department.html")


# edit_department.html 编辑部门
@app.route("/edit_department/<int:id>/",methods=["GET","POST"])
@is_cookie
def edit_department(id):
    department = Department.query.get(id)
    if request.method == "POST":
        # 首先获取这个id的数据
        # 获取表单的数据
        d_name = request.form.get("name")
        d_dec = request.form.get("description")
        # 将数据库中的数据进行更改
        department.d_name = d_name
        department.d_dec = d_dec
        department.update()
        return redirect("/OA/department/")
    return render_template("edit_department.html", **locals())


# 删除部门
@app.route("/delete_dep/<int:id>/")
@is_cookie
def delete_dep(id):
    # 先获取这个数据
    dep = Department.query.get(id)
    # 删除这个数据
    dep.delete()
    return redirect("/OA/department/")


# position 职位管理
@app.route("/position/<int:id>/",methods=["GET", "POST"])
@is_cookie
def position(id):
    der = Department.query.get(id)
    derpot = id
    posi_list = Position.query.filter(Position.pos_department == id)
    if request.method == "POST":
        # 获取新增职位的数据
        if request.form.get("p_name"):
            p_name = request.form.get("p_name")
            p_dec = request.form.get("p_dec")
            # 保存数据到数据库到中
            position = Position()
            position.p_name = p_name
            position.p_dec = p_dec
            position.pos_department = id
            position.save()
            return redirect("/OA/position/{}/".format(id))
        # elif request.form.get("p_name2"):
        #     p_name = request.form.get("p_name2")
        #     p_dec = request.form.get("p_dec2")
    return render_template("position.html", **locals())

# position 职位管理 - 编辑职务

# delete_position 职位管理 - 删除职务
@app.route("/delete_position/<int:derpot>/<int:id>/")
def delete_position(derpot,id):
    # 获取指定职务数据
    post = Position.query.get(id)
    # 删除数据
    post.delete()
    return redirect("/OA/position/{}/".format(derpot))


# person 职员管理
@app.route("/person/",methods=["GET","POST"])
@is_cookie
def person():
    # 获取页面的GET请求
    # 获取所有的部门
    date = request.args
    print(date)
    dep_list = Department.query.all()
    # 获取所有用户详情，并判断是否有GET请求
    if request.args.get("person_username"):
        date = request.args.get("person_username")
        like_name = "%{}%".format(date)
        per_info = PersonInfo.query.filter(PersonInfo.nick_name.like(like_name)).offset(0).limit(20)
        return render_template("person.html", **locals())
    per_info = PersonInfo.query.filter().offset(0).limit(20)
    return render_template("person.html", **locals())



# 获取指定部门的信息
@app.route("/person_info/<int:id>/", methods=["GET","POST"])
@is_cookie
def person_info(id):
    # 获取所有的部门信息
    dep_list = Department.query.all()
    # 判断是否有GET请求
    if request.args.get("person_username"):
        date = request.args.get("person_username")
        like_name = "%{}%".format(date)
        
        per_info = PersonInfo.query.filter(PersonInfo.p_department == id,PersonInfo.nick_name.like(like_name)).offset(0).limit(20)
        return render_template("person.html", **locals())
    per_info = PersonInfo.query.filter(PersonInfo.p_department == id)
    return render_template("person.html",**locals())


# 展示用户详情
@app.route("/detail_person/<int:id>/")
@is_cookie
def detail_person(id):
    per_info = PersonInfo.query.get(id)
    return render_template("detail_person.html", **locals())


# add_person 添加用户
@app.route("/add_person/", methods=["GET","POST"])
@is_cookie
def add_person():
    # 页面展示所有的部门信息
    department_list = Department.query.all()
    if request.method == "POST":
        # 获取POST请求的信息
        username = request.form.get("username")
        password = request.form.get("password")
        nickname = request.form.get("nickname")
        gender = request.form.get("gender")
        age = request.form.get("age")
        phone = request.form.get("phone")
        email = request.form.get("email")
        address = request.form.get("address")
        department = request.form.get("department_id")
        position = request.form.get("position_id")
        posr = Person()
        posr.username = username
        a = setPassword(password)
        posr.password = a
        posr.save()
        por_info = PersonInfo()
        por_info.nick_name = nickname
        por_info.gender = gender
        por_info.age = age
        work_num = int(PersonInfo.query.all()[-1].work_number)+1
        por_info.work_number = str(work_num).zfill(6)
        por_info.phone = phone
        por_info.email = email
        por_info.address = address
        por_info.person_info = posr.id
        por_info.p_department = department
        por_info.p_positon = position
        por_info.save()
        return redirect("/OA/person/")
    return render_template("add_person.html", **locals())


# 编辑用户
@app.route("/edit_person/<int:id>/")
@is_cookie
def edit_person(id):
    # 展示所有的部门和职位
    dep_list = Department.query.all()
    # 获取要修改的id
    person_info = PersonInfo.query.get(id)
    uer = person_info.person_info
    uers = Person.query.get(uer)
    return render_template("edit_person.html", **locals())



# 删除用户
@app.route("/del_perinfo/<int:id>/")
@is_cookie
def del_perinfo(id):
    # 获取这个id对应的两个表
    user_info = PersonInfo.query.get(id)
    Per_id = user_info.person_info
    print(Per_id)
    user = Person.query.get(Per_id)
    user_info.delete()
    user.delete()
    return redirect("/OA/person/")

# 添加信息中根据部门信息返回职位信息
@app.route("/positions/")
def positions():
    d_id = request.args.get("d_id")
    pos_list = [{"p_name":i.p_name,"id": i.id} for i in Department.query.get(d_id).d_position]
    return jsonify({"data":pos_list})

# 编辑信息中根据部门信息返回职位信息
@app.route("/edit_persons/")
def edit_persons():
    de_id = request.args.get("p_id")
    print(de_id)
    pos_list = [{"p_name":i.p_name,"id": i.id} for i in Department.query.get(de_id).d_position]
    return jsonify({"data":pos_list})

# 校验用户名是否重复
@app.route("/has_user/")
def has_user():
    # 获得script传过来的参数
    user = request.args.get("username")
    # 判断数据中是否有重名的用户名
    result = {}
    p = Person.query.filter(Person.username == user).first()
    if p:
        result["d"] = "用户名已经存在"
    else:
        result["d"] = "用户名可以使用"
    return jsonify(result)


